﻿module Sustainalytics.MostRecentActivity {

    export class MostRecentActivityController {

        public activities: MostRecentActivityDto[] = [];
        public skip: number;
        public take: number;

        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $q: ng.IQService,
            private $timeout: ng.ITimeoutService,
            private $location: ng.ILocationService,
            private MostRecentActivityService: IMostRecentActivityService) {

            var ctx = this;

            var initPromise = ctx.init();
        }


        private init(): ng.IPromise<any> {

            var ctx = this;
            ctx.skip = 0;
            ctx.take = 20;

            // load activities
            var activitiesPromise = ctx.showActivities();

            ctx.$scope.$watch('mra.skip', function (newSkip, oldSkip) {
                if (newSkip > oldSkip) {
                    ctx.showActivities();
                }
            });

            return activitiesPromise;
        }


        private showActivities(): ng.IPromise<any> {
            var ctx = this;

            // load activities page
            var activitiesPromise = ctx.MostRecentActivityService.getList(ctx.skip, ctx.take);

            ctx.$rootScope['loading'] = true;

            activitiesPromise.then(function (activities) {
                ctx.$timeout(function () {
                    ctx.$scope.$apply(function () {
                        ctx.activities.push.apply(ctx.activities, activities);
                    })
                });
            });

            activitiesPromise['finally'](function () {
                ctx.$rootScope['loading'] = false;
            });

            return activitiesPromise;
        }


        public goToCompanyPage(activity: MostRecentActivityDto) {
            var ctx = this;
            ctx.$location.url('/research/overview/' + activity.companyNameUrlFriendly);
            
        }
    }


    export var mostRecentActivityControllerName = 'MostRecentActivityController';

    angular.module(mostRecentActivityModuleName).controller(mostRecentActivityControllerName, MostRecentActivityController);
}